// pages/card/card.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        carInfo:{
            cid: '',
        },
        dealerInfo:{},
        userInfo:{},
        seeImages: false,
        imageList:[],
        imageIndex:0,
        modalName:  null, // 
        getFocusByPrice: false,
        subPrice:{
            price:'',
            label:'',
        },
        labelList:['诚心想要','等你还价','合作如何','在线等回'],
        labelApplyList:['诚心想要','等你还价','先看再买','在线等回'],
        userAgreement: true,
        nowCurrent:0, //当前滚动到第几个了。
        applyReportType:'',
        reporType:{
          'c300InsuranceReport':'车300碰撞保险记录',
          'c300MtnceReport':'车300保养维修记录',
          'cbsInsuranceReport':'查博士碰撞保险记录',
          'cbsMtnceReport':'查博士保养维修记录'
        }
    },
    // 分享车辆
    openShare(){
      if (2 != this.data.userInfo.accountStatus) {
          this.showRegister();
          return;
      }
      this.showShareModal();
    },
    showShareModal(){
      // 请求小程序二维码
      app.sHttp.shareqrCode({pageUrl:'pages/card/card',scene:'cid='+this.data.carInfo.carId+'&bsid='+this.data.userInfo.userId}).then(res =>{
        this.selectComponent('#posterComponent').showShareModal(res.base64);
      },err=>{
        app.error(err.msg);
      });
    },

    copyRecommendReasons(){
      let recommendReasons = this.data.carInfo.recommendReasons;
      wx.setClipboardData({
        data: recommendReasons,
        success: function (res) {
          wx.getClipboardData({
            success: function (res) {
              wx.showToast({
                title: '已为您复制推荐理由',
                icon:'none'
              })
            }
          })
        }
      })
  },
    // 下载车辆素材
    downLoadCarImg(e){
      if (2 != this.data.userInfo.accountStatus) {
          this.showRegister();
          return;
      }
      let index = 0;
      this.data.seeImages?index = this.data.imageIndex : index = this.data.nowCurrent;
      // let imagePath = this.data.carInfo.carPicList[index].picUrl;
      let self = this;
      wx.showModal({
        title: '提示',
        content: '您确定下载当前图片包吗？共' + self.data.carInfo.carPicList.length +'张图片。',
        success (res) {
          if (res.confirm) {
            let imageList = self.data.carInfo.carPicList;
            wx.showLoading({
              title: '下载素材中',
              mask: true //默认蒙层。防止触摸穿透
            });
            imageList.forEach((item,index) =>{
              self.downLoadNetImage(item.picUrl,index,self.data.carInfo.carPicList.length);
            })
          }
        }
      })
    },
    downLoadNetImage(path,index,allLong){
      wx.showLoading({
        title: '下载素材中',
        mask: true //默认蒙层。防止触摸穿透
      })
      wx.downloadFile({
        url: path,
        success: function (res) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success () {
              if(index+1 >= allLong){
                wx.hideLoading()
                app.alert("全部素材已保存到您的手机")
                wx.hideLoading();
              }
            },
            fail () {
              wx.hideLoading()
              app.alert("保存失败")
            }
          })
        }
      })
    },
    carImageChange(e){
      this.setData({
        'nowCurrent': e.detail.current
      })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    doNothing(){},
    onLoad: function (options) {
        // 必须一个车辆的ID
        let cid = null;
        if(undefined != options.cid){
          cid = options.cid;
        }else if(options.scene){
          let scanData = decodeURIComponent(options.scene);
          cid = app.GetQueryString(scanData,'cid');
          var value = wx.getStorageSync('user_bsid');
          if(value != undefined && value != 'undefined' && value != null && value != 'null' && value != ''){ 
            app.globalData.shareUserId = value;
          }else{
            if(app.GetQueryString(scanData,'bsid')){
              wx.setStorageSync('user_bsid', app.GetQueryString(scanData,'bsid'));
              app.globalData.shareUserId = app.GetQueryString(scanData,'bsid');
            }else{
                // 当前小程序码已过期，请重新生成海报
              wx.showModal({
                title: '海报过期提醒',
                content: '当前小程序码已过期，请重新生成海报',
                confirmText: '我知道啦',
                showCancel: false,
                success(res) {
                }
              })
            }
          }
        }
        if(cid){
          let self = this;
          this.setData({
              'carInfo.cid': cid
          },()=>{
              self.InitUserStatus();
          });
        }else{
          app.showNoAuthOrNoGrant('未找到您要查看的车辆');
        }
    },
    subRegister(){
      this.InitUserStatus();
    },
    goMaintenance(){
      app.globalData.scopeRowCar = this.data.carInfo
      wx.navigateTo({
        url: '/pages/maintenance/maintenance',
      })
    },
    // 出个价
    sayPrice(){
        if (2 != this.data.userInfo.accountStatus) {
          this.showRegister();
          return;
        }
        this.setData({
            'modalName': 'bargain'
        });
        let self = this;
        setTimeout(() => {
          self.setData({
              'getFocusByPrice': true
          });
        }, 300);
    },
    makePhoneCall(){
        if (2 != this.data.userInfo.accountStatus) {
            this.showRegister();
            return;
        }
        let contactMobile = this.data.dealerInfo.contactMobile;
        if (undefined != contactMobile && null != contactMobile && '' != contactMobile) {
            wx.makePhoneCall({
                phoneNumber: contactMobile,
                success:function(){},
                fail:function(){}
            })
        }else{
            app.alert('未查询到车主电话');
        }
    },doNothing(){},
    subPriceToReq(){
        if (!this.data.userAgreement) {
            app.alert('请勾选允许电话联系哦~');
            return;
        }
        if ('' == this.data.subPrice.price && 0 == this.data.subPrice.price) {
            app.alert('请您填写您要出的价格哦~');
            return;
        }
        // if ('' == this.data.subPrice.label) {
        //     app.alert('请选择标签~');
        //     return;
        // }
        let subPrice = this.data.subPrice;
        subPrice.carId = this.data.carInfo.carId;
        app.sHttp.carCustOfferPrice(subPrice).then(res=>{
            this.setData({
                subPrice:{
                    price:'',
                    label:'',
                }
            })
            this.hideModal();
            app.alert('出价成功，请等待回复哦~');
        },err=>{
            app.error(err.msg);
        })
    },
    showRegister(e) {
      this.registerComponent.showModal();
    },

    // 检查一下登录状态。
    async InitUserStatus(){
        app.showLoading("获取用户信息");
        await app.checkToken();
        this.InitUserInfo();
        wx.hideLoading();
    },
    InitUserInfo(){
        this.setData({
            'userInfo': app.globalData.userInfo
        });
        this.registerComponent = this.selectComponent('#registerComponent');
        this.registerComponent.lifeInit();
        app.sHttp.carCustView(this.data.carInfo.cid).then(res=>{
          let imageList = [];
          res.result.carInfo.carPicList.forEach(item =>{
              imageList.push(item.picUrl);
          });
          if(res.result.carInfo.insuranceReportType || res.result.carInfo.mtnceReportType){
            res.result.carInfo.haveReport = true;
          }else{
            res.result.carInfo.haveReport = false;
          }
          // 处理三个时间，
          res.result.carInfo.licensingTime = this.handleTimesForRI(res.result.carInfo.licensingTime || '');
          res.result.carInfo.compulsoryInsuranceTime = this.handleTimesForRI(res.result.carInfo.compulsoryInsuranceTime);
          res.result.carInfo.yearlyInspectionTime = this.handleTimesForRI(res.result.carInfo.yearlyInspectionTime);
          this.setData({
              'imageList': imageList,
              'carInfo': res.result.carInfo,
              'dealerInfo': res.result.dealerInfo
          })
        },err=>{
            let self = this;
            setTimeout(() => {
                self.BackPage();
            }, 1500);
        })
    },
    handleTimesForRI(time){
        if (time.indexOf('日') != -1 && time.indexOf('月') != -1) {
            return time.substring(0,time.indexOf('月')+1);
        }
        return time;
    },
    BackPage() {
      var that = this;
      wx.navigateBack({
        delta: 1,
        fail: function(){
          that.toHome();
        }
      });
    },
    toHome(){
      wx.reLaunch({
        url: '/pages/home/home',
      })
    },
    doNothing(e){
    },
    switchSeeImage(e){
        let imageIndex = e.currentTarget.dataset.idx;
        let self = this;
        this.setData({
            'imageIndex': imageIndex,
            'seeImages': !self.data.seeImages
        })
    },
    seeImgeChange(e){
        this.setData({
            'imageIndex': e.detail.current
        })
    },
    showModal(e) {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    },
    hideModal(e) {
      this.setData({
        'modalName': null,
        'getFocusByPrice': false
      })
    },
    changeIcon(e){
        this.setData({
            'subPrice.label': e.currentTarget.dataset.item
        })
    },
    publishInput(e){
        this.setData({
            'subPrice.price': e.detail.value
        })
    },
    useUserAgreement(){
      this.setData({
        userAgreement: !this.data.userAgreement
      })
    },
    seeOrapply(e){
      let url = e.currentTarget.dataset.url;
      if(url){
        app.globalData.lookReportInfoUrl = url;
        wx.navigateTo({
          url: '/pages/carQueryRecord/detailed/detailed',
        })
      }else{
        this.setData({
          'modalName':'reportApply',
          'applyReportType': e.currentTarget.dataset.type
        })
      }
    },
    goApplyReport(){
      // 申请操作。
      app.sHttp.reportApply({carId:this.data.carInfo.carId,reportType:this.data.applyReportType}).then(res=>{
        this.hideModal();
        app.alert('申请已提交,请等待回复~');
      },err=>{
        app.error(err.msg);
      })
    },
})